package jsu.blogger.service.impl;

import jsu.blogger.filter.DataFilter;
import jsu.blogger.mapper.UserStatsMapper;
import jsu.blogger.mapper.UsersMapper;
import jsu.blogger.pojo.Users;
import jsu.blogger.pojo.VerificationCode;
import jsu.blogger.service.RedisService;
import jsu.blogger.util.EmailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginAndRegisterServiceImpl implements jsu.blogger.service.inter.LoginAndRegisterService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserStatsMapper userStatsMapper;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private RedisService redisService;
    private static final Logger log = LoggerFactory.getLogger(DataFilter.class);
    @Override
    public Long login(String email, String password, String currentDevice) {
        Long res= (long) -1;
        Long UId= userStatsMapper.selectUIdByEmail(email);
        if(UId!=null){
            Users user=usersMapper.selectUserByUId(UId);
            if(user!=null&&user.getPassword().equals(password)){
                res=UId;
                usersMapper.updateUserCurrentDeviceByUId(currentDevice,UId);
                log.info("UID:"+UId+" 用户"+user.getUsername() + "登录");
            }
        }

        return res;
    }

    @Override
    @Transactional
    public int Register(String email, String password, VerificationCode verificationCode) {
        int register=0;
        System.out.println(verificationCode);
        //System.out.println("ce");
        register=this.VerifyTheVerificationCode(verificationCode);
        if(register==2){
            Users user=new Users("用户"+new Random().nextInt(1000000),password,"firstRegister");
            try {
                usersMapper.insertUser(user);
                System.out.println(user);
            }catch (Exception e){
                System.out.println(e);
            }

            userStatsMapper.insertUserStats(user.getUserId(),email);
            register++;
        }
        return register;//0验证码错误 1验证码过期 2未知异常 3注册成功
    }
    public int changeAccount(String email,  VerificationCode verificationCode) {
        int register=0;
        System.out.println(verificationCode);
        //System.out.println("ce");
        register=this.VerifyTheVerificationCode(verificationCode);
        if(register==2){
            Users user=new Users("用户"+new Random().nextInt(1000000),"firstRegister");
            try {
//                usersMapper.insertUser(user);
                System.out.println(user);
            }catch (Exception e){
                System.out.println(e);
            }

//            userStatsMapper.insertUserStats(user.getUserId(),email);
            register++;
        }
        return register;//0验证码错误 1验证码过期 2未知异常 3注册成功
    }

    public Boolean VerifyUIdAndPassword(Long UId,String password){
        String verifyPassword=usersMapper.selectPasswordByUId(UId);
        return verifyPassword.equals(password);
    }

    public boolean sendRegisterEmailVerifyCode(String email){
        if(userStatsMapper.selectUIdByEmail(email)==null){
            int min=100000;
            int max=999999;
            String code= String.valueOf((new Random().nextInt(max-min+1))+min);
            log.info("注册验证码："+code);
            emailUtil.sendEmail(email,"LINK邮箱注册验证码","验证码:"+code+",打死也不要告诉别人哦");
            VerificationCode verificationCode=new VerificationCode(email,code, LocalDateTime.now());
            try {
                redisService.setValueWithExpiry("EmailVerifyCode_"+email,verificationCode,10, TimeUnit.MINUTES);
            }catch (Exception e){
                System.out.println(e);
            }
            return true;
        }
        return false;
    }
    public boolean sendEmailVerifyCode(String email){
            int min=100000;
            int max=999999;
            String code= String.valueOf((new Random().nextInt(max-min+1))+min);
            log.info("注册验证码："+code);
            emailUtil.sendEmail(email,"LINK邮箱注册验证码","验证码:"+code+",打死也不要告诉别人哦");
            VerificationCode verificationCode=new VerificationCode(email,code, LocalDateTime.now());
            try {
                redisService.setValueWithExpiry("EmailVerifyCode_"+email,verificationCode,10, TimeUnit.MINUTES);
            }catch (Exception e){
                System.out.println(e);
            }
            return true;


    }


    private int VerifyTheVerificationCode(VerificationCode verificationCode){
        int verifyTheVerificationCode=0;
        VerificationCode code = redisService.getValue("EmailVerifyCode_"+verificationCode.getEmail(),VerificationCode.class);
        if(code.getCode().equals(verificationCode.getCode())){
            verifyTheVerificationCode++;
            long minutes = ChronoUnit.MINUTES.between(code.getCreatTime(), verificationCode.getCreatTime());
            //System.out.println(minutes);
            if(minutes<50){
                verifyTheVerificationCode++;
                System.out.println("验证码的状态"+verifyTheVerificationCode);
            }
        }
        return verifyTheVerificationCode;//0验证码错误 1验证码过期 2通过
    }
}
